@extends('user_center.master')

@section('title')
    我的地址-个人中心
@endsection

@section('info-title')
    我的地址
@endsection

@section('content')
    <el-row class="location_box" v-for="(item,index) in myAddresses" :key="item.id">
        <el-col :sm="12" :xs="12" :md="16">
            <el-row>
                <el-col class="location">
                    @{{item.province}} |
                    @{{item.city}} |
                    @{{item.county}} |
                    @{{item.region}} |
                    @{{item.phone}} |
                    —— @{{ item.name }}
                </el-col>
            </el-row>
            <el-row>
                <el-col class="detail-address">
                    @{{ item.detail_address}}
                </el-col>
            </el-row>
        </el-col>

        <el-col :sm="8" :xs="7" :md="4" :offset="3" class="options">
            <el-row>
                <el-button size="mini" class="btn_option" @click="openAddressDrawer('edit',item,index)">编辑</el-button>
            </el-row>
            <el-row>
                <el-button size="mini" type="danger" class="btn_option" @click="deleteAddress(item.id,index)">删除
                </el-button>
            </el-row>
        </el-col>
    </el-row>


    <el-row>
        <el-col :md="24">
            <el-button v-if="!btnAddDisabled" class="el-icon-circle-plus btn_add btn_option"
                       @click="openAddressDrawer('add')">
            </el-button>

            <el-tooltip v-else class="item" effect="dark" content="最多只能添加5个地址信息" placement="top">
                <el-button class="el-icon-circle-plus btn_add btn_option btnAddDisabled">
                </el-button>
            </el-tooltip>
        </el-col>
    </el-row>


    <el-drawer
        :visible.sync="drawer_AddressVisible"
        :with-header="false"
        direction="rtl"
        :modal="false"
        ref="drawer"
        :before-close="handleClose"
        class="drawer_address">

        <el-form class="select_box" label-width="150px" :model="selectAddress" ref="form-address" :rules="rules"
                 :hide-required-asterisk="true">
            <el-form-item label="收货人" prop="name">
                <el-input v-model="selectAddress.name" placeholder="收货人姓名"></el-input>
            </el-form-item>

            <el-form-item label="联系电话" prop="phone">
                <el-input v-model="selectAddress.phone" placeholder="收货人联系电话"></el-input>
            </el-form-item>


            <el-form-item label="请选择省市/地区" prop="selectProvince">
                <el-select v-model="selectAddress.selectProvince" placeholder="请选择省市/地区" @change="provinceChange">
                    <el-option
                        v-for="item in provinces"
                        :key="item.province_id"
                        :label="item.province_name"
                        :value="item.province_id">
                    </el-option>
                </el-select>
            </el-form-item>


            <el-form-item label="请选择城市/地区" prop="selectCity">
                <el-select v-model="selectAddress.selectCity" placeholder="请选择城市/地区" :disabled="cityEnable"
                           @change="cityChange">
                    <el-option
                        v-for="item in cities"
                        :key="item.city_id"
                        :label="item.city_name"
                        :value="item.city_id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="请选择城镇/地区" prop="selectCounty">
                <el-select v-model="selectAddress.selectCounty" placeholder="请选择城镇/地区" :disabled="countyEnable"
                           @change="countyChange">
                    <el-option
                        v-for="item in counties"
                        :key="item.county_id"
                        :label="item.county_name"
                        :value="item.county_id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="请选择地区" prop="selectRegion">
                <el-select v-model="selectAddress.selectRegion" placeholder="请选择地区" :disabled="regionEnable"
                           @change="regionChange">
                    <el-option
                        v-for="item in regions"
                        :key="item.town_id"
                        :label="item.town_name"
                        :value="item.town_id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="详细地址" prop="detailAddress">
                <el-input class="inp-detailed-address" type="textarea" placeholder="请填写详细地址"
                          v-model="selectAddress.detailAddress">
                </el-input>
            </el-form-item>

            <el-form-item>
                <el-button @click="closeDrawer">关 闭</el-button>
                <el-button type="primary" @click="addOrEditAddress">提 交</el-button>
            </el-form-item>

        </el-form>
    </el-drawer>

@endsection

@section('js_css')
    <script>
        var app = new Vue({
            el: '#app',
            data() {
                var checkPhone = (rule, value, callback) => {
                    const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
                    if(value === ''){
                        callback(new Error('请输入电话号码'));
                    }else if(!reg.test(value)){
                        callback(new Error('请输入正确的11位手机号码'));
                    }else{
                        callback();
                    }
                };
                return {
                    activeItem: [false, false, false, false, true, false, false, false, false, false, false],
                    user:@json(Auth::user()),  //must has

                    provinces: (@json($data)).provinces,
                    cities: [],
                    counties: [],
                    regions: [],
                    cityEnable: true,
                    countyEnable: true,
                    regionEnable: true,


                    myAddresses: (@json($data)).myAddresses,
                    drawerAddress: {},
                    drawer_AddressVisible: false,


                    selectAddress: {
                        phone: '',
                        name: '',
                        selectProvince: '',
                        selectCity: '',
                        selectCounty: '',
                        selectRegion: '',
                        detailAddress: '',
                        currentId: ''
                    },
                    currentIndex: '',

                    drawerOption: '',
                    selectProvinceName: '',
                    selectCityName: '',
                    selectCountyName: '',
                    selectRegionName: '',


                    rules: {
                        name: [{required: true, message: '收货人不能为空', trigger: ['blur','change']}],
                        phone: [{ validator: checkPhone, trigger: ['blur','change'] }],
                        selectProvince: [{required: true, message: '请选择省市/地区', trigger: ['blur','change']}],
                        selectCity: [{required: true, message: '请选择城市/地区', trigger: ['blur','change']}],
                        selectCounty: [{required: true, message: '请选择城镇/地区', trigger: ['blur','change']}],
                        selectRegion: [{required: true, message: '请选择地区', trigger: ['blur','change']}],
                        detailAddress: [{required: true, message: '详细地址不能为空', trigger: ['blur','change']}],
                    }
                };
            },
            methods: {
                openAddressDrawer(option, item = '', index = '') {
                    //清空输入框
                    if (option === 'add') {
                        app.selectAddress.name = '';
                        app.selectAddress.phone = '';
                        app.selectAddress.selectProvince = '';
                        app.selectAddress.selectCity = '';
                        app.selectAddress.selectCounty = '';
                        app.selectAddress.selectRegion = '';
                        app.selectAddress.detailAddress = '';
                        app.selectAddress.currentId = '';
                        app.selectProvinceName = '';
                        app.selectCityName = '';
                        app.selectCountyName = '';
                        app.selectRegionName = '';
                    } else if (option === 'edit') {
                        app.selectAddress.name = item.name;
                        app.selectAddress.phone = item.phone;
                        app.selectAddress.detailAddress = item.detail_address;
                        app.provinceChange(item.province_id);
                        app.cityChange(item.city_id);
                        app.countyChange(item.county_id);
                        app.selectAddress.selectProvince = parseInt(item.province_id);
                        app.selectAddress.selectCity = parseInt(item.city_id);
                        app.selectAddress.selectCounty = parseInt(item.county_id);
                        app.selectAddress.selectRegion = parseInt(item.region_id);
                        app.selectAddress.currentId = item.id;
                        app.currentIndex = index;
                        app.selectProvinceName = item.province;
                        app.selectCityName = item.city;
                        app.selectCountyName = item.county;
                        app.selectRegionName = item.region;
                    }
                    app.drawerOption = option;
                    app.drawer_AddressVisible = true;
                },
                //当省份改变时 加载省份对应城市 清楚并禁用城镇与地区选择框
                provinceChange(selectItem) {
                    app.selectAddress.selectProvince = parseInt(selectItem);
                    this.cities = [];
                    this.selectAddress.selectCity = '';
                    this.selectAddress.selectCounty = '';
                    this.selectAddress.selectRegion = '';
                    this.countyEnable = true;
                    this.regionEnable = true;
                    for (let i = 0; i < this.provinces.length; i++) {
                        if (this.provinces[i].province_id === selectItem) {
                            app.selectProvinceName = this.provinces[i].province_name;
                            break;
                        }
                    }
                    axios.get('/user/getCity/' + selectItem)
                        .then(res => {
                            res.data.data.forEach((item, index) => {
                                app.cities.push(item);
                            });
                            app.cityEnable = false;
                        })
                        .catch(err => {
                            app.noticeError('获取城市数据失败，请刷新重试！');
                            console.log(err);
                        })
                },
                //当城市改变时 加载城市对应城镇  启用城镇选择框 清楚并地区选择框
                cityChange(selectItem) {
                    app.selectAddress.selectCity = parseInt(selectItem);
                    this.counties = [];
                    this.selectAddress.selectCounty = '';
                    this.selectAddress.selectRegion = '';
                    this.regionEnable = true;
                    for (let i = 0; i < this.cities.length; i++) {
                        if (this.cities[i].city_id === selectItem) {
                            app.selectCityName = this.cities[i].city_name;
                            break;
                        }
                    }
                    axios.get('/user/getCounty/' + selectItem)
                        .then(res => {
                            res.data.data.forEach((item, index) => {
                                app.counties.push(item);
                            });
                            app.countyEnable = false;
                        })
                        .catch(err => {
                            app.noticeError('获取城镇数据失败，请刷新重试！');
                            console.log(err);
                        })
                },
                //当城镇改变时 加载城镇对应地区  启用区选择框
                countyChange(selectItem) {
                    app.selectAddress.selectCounty = parseInt(selectItem);
                    this.regions = [];
                    this.selectAddress.selectRegion = '';
                    for (let i = 0; i < this.counties.length; i++) {
                        if (this.counties[i].county_id === selectItem) {
                            app.selectCountyName = this.counties[i].county_name;
                            break;
                        }
                    }

                    axios.get('/user/getRegion/' + selectItem)
                        .then(res => {
                            res.data.data.forEach((item, index) => {
                                app.regions.push(item);
                            });
                            app.regionEnable = false;
                        })
                        .catch(err => {
                            app.noticeError('获取地区数据失败，请刷新重试！');
                            console.log(err);
                        })
                },
                regionChange(selectItem) {
                    app.selectAddress.selectRegion = parseInt(selectItem);
                    for (let i = 0; i < this.regions.length; i++) {
                        if (this.regions[i].town_id === selectItem) {
                            app.selectRegionName = this.regions[i].town_name;
                            break;
                        }
                    }
                },

                addOrEditAddress() {
                    let check = false;
                    this.$refs['form-address'].validate(result => {
                        check = result;
                    });
                    if (!check) {
                        this.noticeWarning('请将数据填写完整！');
                        return false;
                    }
                    let data = new FormData();
                    data.append('name', app.selectAddress.name);
                    data.append('phone', app.selectAddress.phone);
                    data.append('province_id', app.selectAddress.selectProvince);
                    data.append('province', app.selectProvinceName);
                    data.append('city_id', app.selectAddress.selectCity);
                    data.append('city', app.selectCityName);
                    data.append('county_id', app.selectAddress.selectCounty);
                    data.append('county', app.selectCountyName);
                    data.append('region_id', app.selectAddress.selectRegion);
                    data.append('region', app.selectRegionName);
                    data.append('detail_address', this.selectAddress.detailAddress);
                    data.append('user_id', app.user.id);
                    if (app.drawerOption === 'add') {
                        axios.post('/user/myAddress/add', data)
                            .then(res => {
                                if (res.data.status_code === 200) {
                                    app.myAddresses.push(res.data.data);
                                    app.drawer_AddressVisible = false;
                                    app.noticeSuccess(res.data.message);
                                } else {
                                    app.noticeWarnings(res.data.error);
                                }
                            })
                            .catch(err => {
                                app.noticeError('哦豁！服务器出BUG了!GG，请刷新重试！');
                                console.log(err)
                            })
                    } else if (app.drawerOption === 'edit') {
                        data.append('id', app.selectAddress.currentId);
                        axios.post('/user/myAddress/change', data)
                            .then(res => {
                                if (res.data.status_code === 200) {
                                    app.myAddresses.splice(app.currentIndex, 1, res.data.data);
                                    app.drawer_AddressVisible = false;
                                    app.noticeSuccess(res.data.message);
                                } else {
                                    app.noticeWarnings(res.data.error);
                                }
                            })
                            .catch(err => {
                                app.noticeError('哦豁！服务器出BUG了!GG，请刷新重试！');
                                console.log(err)
                            })
                    }

                },
                deleteAddress(id, index) {
                    this.$confirm('确定要删除吗?')
                        .then(() => {
                            axios.delete('/user/myAddress/delete/' + id)
                                .then(res => {
                                    app.myAddresses.splice(index, 1);
                                    app.noticeSuccess(res.data.message);
                                })
                                .catch(err => {
                                    app.noticeError('服务器错误！请刷新重试');
                                    console.log(err);
                                })
                        })
                        .catch(() => {
                        });
                },
                closeDrawer() {
                    this.$refs['drawer'].closeDrawer();
                },
                handleClose(done) {
                    app.selectAddress.selectProvince = '';
                    app.cityEnable = true;
                    app.countyEnable = true;
                    app.regionEnable = true;
                    app.selectAddress.selectCity = '';
                    app.selectAddress.selectCounty = '';
                    app.selectAddress.selectRegion = '';
                    done();
                },

                //成功提示
                noticeSuccess(message) {
                    this.$notify.success({
                        title: '提示',
                        message: message
                    });
                },
                //错误提示
                noticeError(err) {
                    this.$notify.error({
                        title: '错误',
                        message: err
                    })
                },
                //警告提示
                noticeWarning(message) {
                    this.$notify.warning({
                        title: '提示',
                        message: message
                    })
                },
                //多警告提示
                noticeWarnings(messages) {
                    messages.forEach((item, index) => {
                        setTimeout(function () {
                            this.$notify.warning({
                                title: '提示',
                                message: item
                            })
                        }, 1);
                    });
                }
            },
            computed: {
                btnAddDisabled: function () {
                    return this.myAddresses.length < 5 ? false : true;
                }
            }
        })
    </script>

    <style>
        .location_box {
            height: 100px;
            line-height: 40px;
            margin-top: 20px;
            padding-left: 50px;
            border-bottom: 1px #dddddd solid;
        }

        .options {
            height: 100px;
            line-height: 40px;
        }

        .btn_add {
            width: 100%;
            height: 60px;
            font-size: 2em;
            margin-top: 20px;
        }

        .drawer_address .el-form {
            padding-top: 35%;
        }

        .drawer_address .el-form-item {
            width: 80%;
            margin: 40px auto;
        }

        .drawer_address .el-form-item:last-child {
            margin-top: 80px;
        }

        .drawer_address .el-form-item .el-select {
            width: 100% !important;
        }

        .btnAddDisabled {
            background-color: white;
            color: rgb(192, 196, 204);
        }

        .btnAddDisabled:hover, .btnAddDisabled:focus {
            cursor: no-drop;
            background-color: white;
            color: rgb(192, 196, 204);
            border: 1px rgb(192, 196, 204) solid;
        }

    </style>
@endsection
